<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 9:18:47
 * Info: 后台基类
 */

namespace app\admin\controller;

use think\App;
use think\exception\ValidateException;
use think\facade\View;
use think\Validate;

class Base
{

    use \app\common\traits\JumpTrait;

    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;

    /**
     * 字段排序
     * @var array
     */
    protected $sort = [
        'id' => 'desc',
    ];

    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFields = [
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'title',
    ];

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        $this->checkIp();
    }

    /**
     * 构造方法
     * @access public
     *
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
        View::assign('version', config('cms.version'));
    }

    /**
     * 后台IP禁止判断
     */
    final public function checkIp()
    {
        //获取客户ip
        $ip = get_client_ip();
        //获取系统配置admin_prohibit_ip信息
        $admin_prohibit_ip = get_config('admin_prohibit_ip');
        if (empty($admin_prohibit_ip)) {
            return true;
        }
        $arr = explode(',', $admin_prohibit_ip);
        foreach ($arr as $val) {
            //是否是IP段
            if (strpos($val, '*')) {
                if (strpos($ip, str_replace('.*', '', $val)) !== false) {
                    $this->returnJson(['code' => 0, 'msg' => '你在IP禁止段内,禁止访问！~~~']);
                }
            } else {
                //不是IP段,用绝对匹配
                if ($ip == $val) {
                    $this->returnJson(['code' => 0, 'msg' => 'IP地址绝对匹配,禁止访问！~~~']);
                }
            }
        }
    }

    /**
     * 重写验证规则
     *
     * @param array        $data
     * @param array|string $validate
     * @param array        $message
     * @param bool         $batch
     *
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = null)
    {
        try {
            $this->validateError($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        return true;
    }

    /**
     * 验证数据
     * @access protected
     *
     * @param array        $data     数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array        $message  提示信息
     * @param bool         $batch    是否批量验证
     *
     * @return array|string|true
     * @throws ValidateException
     */
    private function validateError(array $data, $validate, array $message = [], bool $batch = null)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if ( ! empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 返回json数组
     *
     * @param $arr
     *
     * @return void
     */
    function returnJson($arr = [])
    {
        header('Content-Type:application/json; charset=utf-8');
        die(json_encode($arr, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 接收序列化数据处理
     * @return void
     */
    public static function input()
    {
        $post = file_get_contents('php://input');
        if (strpos($post, '=')) {
            parse_str($post, $data);
            $post = $data;
        } else {
            $post = json_decode($post, true);
        }

        return $post;
    }
}
